<?php
$db = new Database;
$auth = Auth::getAuth('current_user');
$user_id = $auth['id'];
$user_group = $auth['role'];
$user_groupType = $auth['role_type'];
$company_id = $auth['company_id'];
if(isset($_POST['action'])){
    if($_POST['action']=="setFirstApprover"){
        $getActiveOrgChart = $db->query("SELECT id FROM tborgchart where is_active = 1 and company_id='$company_id' and status=1","row");
        $getObjectID = $db->query("SELECT object_id from tborgchartobjects where role='$user_group' and orgChart_id='".$getActiveOrgChart['id']."'","row");
        $form_id = $_POST['form_id'];
        $getWorkflow_id = $db->query("SELECT workflow_id FROM tbform where id='$form_id'","row");
        $master = $db->query("SELECT child_id FROM tbworkflow_line where master_id = 'flowspan_1_worklow' and worflow_id = '".$getWorkflow_id['workflow_id']."'","row");
        $valid = 1;
        if(!empty($master['child_id'])){
            while(true){
                if($d==0){
                    $master = $db->query("SELECT child_id FROM tbworkflow_line where master_id = 'flowspan_1_worklow' and worflow_id = '".$getWorkflow_id['workflow_id']."'","row");    
                }else{
                    $master = $db->query("SELECT child_id FROM tbworkflow_line where master_id = '".$master['child_id']."' and worflow_id = '".$getWorkflow_id['workflow_id']."'","row");    
                }
                $queryMasterNode = $db->query("SELECT * FROM tbworflow_obects where object_id='".$master['child_id']."' and worflow_id = '".$getWorkflow_id['workflow_id']."'","row");
                if($queryMasterNode['role']=="END"){
                    break;
                }else{
                    if($queryMasterNode['role']=="Head" || $queryMasterNode['role']=="Assistant Head"){
                        //FOR HEAD OR ASSISTANT
                        if($d==0 && $user_groupType!=1){
                            $userRole = $user_group;
                            $approver =  $queryMasterNode['role']."_".$user_group;
                            $masterOrgChart = $db->query("SELECT object_id FROM tborgchartobjects where role='$user_group' and orgChart_id = '".$getActiveOrgChart['id']."'","row");
                        }else{
                            if($d==0){
                                $masterOrgChart = $db->query("SELECT master_id FROM tborgchartline where child_id = '".$getObjectID['object_id']."' and orgChart_id = '".$getActiveOrgChart['id']."'","row");    
                            }else{
                                $masterOrgChart = $db->query("SELECT master_id FROM tborgchartline where (child_id = '".$masterOrgChart['master_id']."' || child_id='".$masterOrgChart['object_id']."') and orgChart_id = '".$getActiveOrgChart['id']."'","row");    
                            }
                            $queryMasterNodeOrgChart = $db->query("SELECT * FROM tborgchartobjects where object_id='".$masterOrgChart['master_id']."' and orgChart_id = '".$getActiveOrgChart['id']."'","row");
                            $approver =  $queryMasterNode['role']."_".$queryMasterNodeOrgChart['role'];
                            $userRole = $queryMasterNodeOrgChart['role'];
                        }
                        $getRowsApprover = $db->query("SELECT * FROM tbuser where role_type='".tempGroupType($queryMasterNode['role'])."' and role='$userRole' and is_active=1 and status =1","numrows");;
                        if($getRowsApprover>0){
                            $lastApproverCount++;
                        }
                    }else{
                        //FOR SPECIFIC USER OR POSITION
                        $getRowsApprover = $db->query("SELECT * FROM tbuser u LEFT JOIN tbposition p on u.position_id = p.id where concat_ws(' ',u.firstname,u.lastname) = '".$queryMasterNode['role']."' or p.position = '".$queryMasterNode['role']."' and u.is_active=1 and u.status =1","numrows");
                        if($getRowsApprover>0){
                            $approver = $queryMasterNode['role'];
                            $lastApproverCount++;
                        }
                    }
                    if($lastApproverCount>0){
                        $master_id = $queryMasterNode['object_id'];
                        $approverStatus = $queryMasterNode['status'];
                        //echo $approver."->".$master_id."->".$approverStatus."\n";
                        $insertRequestProcess = array(
                                    "request_id"=>$_POST['request_id'],
                                    "approver"=>$approver,
                                    "approverStatus"=>$approverStatus,
                                    "wf_master_id"=>$master_id,
                                    "status"=>0
                            );
                        
                        $requestProcess_id = $db->insert("tbrequest_process",$insertRequestProcess);
                        echo 1;
                        break;
                    }
                }
                $d++;
            }
        }else{
            echo "0";
            $valid = 0;
        }
        if($lastApproverCount==0){
            $deleteRequest = array(
                "id"=>$_POST['request_id']
                );
            $db->delete("tbrequest",$deleteRequest);
            echo "No Approver";
            $valid = 0;
        }
    }else if($_POST['action']=="setNextApprover"){
        $request_id = explode(",",implode(",",$_POST['request_id']));
        $nextMaster_id = explode(",",implode(",",$_POST['nextMaster_id']));
        $requestProcess_idArray = explode(",",implode(",",$_POST['requestProcess_id']));
        for($a=0;$a<count($request_id);$a++){
            $updateDone = 0;
            //echo $_POST['requestProcess_id'];
            //next process is to insert the next approver or to update the request to finish
            $getworkflow_id = $db->query("SELECT f.workflow_id FROM tbrequest r LEFT JOIN tbform f on r.form_id =f.id where r.id='$request_id[$a]'","row");
            $master = $db->query("SELECT child_id FROM tbworkflow_line where master_id = '".$nextMaster_id[$a]."' and worflow_id = '".$getworkflow_id['workflow_id']."'","row");
            $getWorkFlowGroup = $db->query("SELECT * FROM tbworflow_obects where object_id='".$master['child_id']."' and worflow_id = '".$getworkflow_id['workflow_id']."'","row");
            $approverStatus = $getWorkFlowGroup['status'];
            //echo $getworkflow_id['workflow_id'];
            //echo $getWorkFlowGroup['role']; group type
            $pos = strpos($getWorkFlowGroup['object_id'],"endOfDiagram");
            if($pos==true){
                echo "Last Approver";
                $updateDone +=1;
            }else{
                if($master['child_id']!=""){
                    $getActiveOrgChart = $db->query("SELECT id FROM tborgchart where is_active = 1 and company_id='$company_id' and status=1","row");
                    $getObjectID = $db->query("SELECT object_id from tborgchartobjects where role='$user_group' and orgChart_id='".$getActiveOrgChart['id']."'","row");
                    $getMasterObjectID = $db->query("SELECT master_id from tborgchartline where child_id='".$getObjectID['object_id']."' and orgChart_id='".$getActiveOrgChart['id']."'","row");
                    $getOrgChartGroup = $db->query("SELECT role,object_id from tborgchartobjects where object_id='".$getMasterObjectID['master_id']."' and orgChart_id='".$getActiveOrgChart['id']."'","row");
                    $lastApproverCount = 0;
                    $d = 0;
                    while(true){
                        //FOR WORKFLOW ROLE
                        if($d==0){
                            $master = $db->query("SELECT child_id FROM tbworkflow_line where master_id = '".$nextMaster_id[$a]."' and worflow_id = '".$getworkflow_id['workflow_id']."'","row");    
                        }else{
                            $master = $db->query("SELECT child_id FROM tbworkflow_line where master_id = '".$master['child_id']."' and worflow_id = '".$getworkflow_id['workflow_id']."'","row");    
                        }
                        $queryMasterNode = $db->query("SELECT * FROM tbworflow_obects where object_id='".$master['child_id']."' and worflow_id = '".$getworkflow_id['workflow_id']."'","row");
                        //FOR ORGCHART ROLE
                        if($queryMasterNode['role']=="END"){
                            break;
                        }else{
                            if($queryMasterNode['role']=="Head" || $queryMasterNode['role']=="Assistant Head"){
                                //FOR HEAD OR ASSISTANT
                                if($d==0 && $user_groupType==2 && $queryMasterNode['role']=="Head"){
                                    $userRole = $user_group;
                                    $approver =  $queryMasterNode['role']."_".$user_group;
                                    $masterOrgChart = $db->query("SELECT object_id FROM tborgchartobjects where role='$user_group' and orgChart_id = '".$getActiveOrgChart['id']."'","row");
                                }else{
                                    if($d==0){
                                        $masterOrgChart = $db->query("SELECT master_id FROM tborgchartline where child_id = '".$getObjectID['object_id']."' and orgChart_id = '".$getActiveOrgChart['id']."'","row");    
                                    }else{
                                        $masterOrgChart = $db->query("SELECT master_id FROM tborgchartline where (child_id = '".$masterOrgChart['master_id']."' || child_id='".$masterOrgChart['object_id']."') and orgChart_id = '".$getActiveOrgChart['id']."'","row");    
                                    }
                                    $queryMasterNodeOrgChart = $db->query("SELECT * FROM tborgchartobjects where object_id='".$masterOrgChart['master_id']."' and orgChart_id = '".$getActiveOrgChart['id']."'","row");
                                    $approver =  $queryMasterNode['role']."_".$queryMasterNodeOrgChart['role'];
                                    $userRole = $queryMasterNodeOrgChart['role'];
                                }
                                $getRowsApprover = $db->query("SELECT * FROM tbuser where role_type='".tempGroupType($queryMasterNode['role'])."' and role='$userRole' and is_active=1 and status =1","numrows");
                                if($getRowsApprover>0){
                                    $lastApproverCount++;
                                }
                            }else{
                                //FOR SPECIFIC USER OR POSITION
                                $getRowsApprover = $db->query("SELECT * FROM tbuser u LEFT JOIN tbposition p on u.position_id = p.id where concat_ws(' ',u.firstname,u.lastname) = '".$queryMasterNode['role']."' or p.position = '".$queryMasterNode['role']."' and u.is_active=1 and u.status =1","numrows");
                                if($getRowsApprover>0){
                                    $approver = $queryMasterNode['role'];
                                    $lastApproverCount++;
                                }
                            }
                            if($lastApproverCount>0){
                                $master_id = $queryMasterNode['object_id'];
                                $approverStatus = $queryMasterNode['status'];
                                //echo $approver."->".$master_id."->".$approverStatus;
                                $insertRequestProcess = array(
                                            "request_id"=>$request_id[$a],
                                            "approver"=>$approver,
                                            "approverStatus"=>$approverStatus,
                                            "wf_master_id"=>$master_id,
                                            "status"=>0
                                    );
                                $requestProcess_id = $db->insert("tbrequest_process",$insertRequestProcess);
                                break;
                            }
                        }
                        $d++;
                    }
                }else{
                    echo "Last Approver(Workflow)";
                    $updateDone +=1;
                    //update the request status = 1
                }    
            }
            if($lastApproverCount==0){
                echo "Last Approver (No next Approver)";
                $updateDone +=1;
            }
            if($updateDone>0){
                //done
                $updateReq = array(
                    "status"=>1,
                    "updated_by"=>$user_id
                    );
                $conditionReq = array(
                    "id"=>$request_id[$a]
                    );
                $db->update("tbrequest",$updateReq,$conditionReq);
                //Update status = 2 means last approver
                $update = array(
                    "status"=>2,
                    "approvedBy"=>$user_id
                    );
                $condition = array(
                    "id"=>$requestProcess_idArray[$a]
                    );
                $db->update("tbrequest_process",$update,$condition);
            }else{
                //Update status = 1 means approved then insert another approver!
                $update = array(
                    "status"=>1,
                    "approvedBy"=>$user_id
                    );
                $condition = array(
                    "id"=>$requestProcess_idArray[$a]
                    );
                $db->update("tbrequest_process",$update,$condition);
            }
        }
    }else if($_POST['action']=="rejectRequest"){
        $request_id = explode(",",implode(",",$_POST['request_id']));
        $requestProcess_idArray = explode(",",implode(",",$_POST['requestProcess_id']));
        print_r($request_id);
        echo "\n";
        print_r($requestProcess_idArray);
        for($a=0;$a<count($request_id);$a++){
            //request
            $update = array(
                "status"=>2,
                "updated_by"=>$user_id
                );
            $condition = array(
                "id"=>$request_id[$a]
                );
            echo $db->update("tbrequest",$update,$condition);
            //request process
            $updateReqProc = array(
                "status"=>2,
                "approvedBy"=>$user_id
                );
            $conditionReqProc = array(
                "id"=>$requestProcess_idArray[$a]
                );
            $db->update("tbrequest_process",$updateReqProc,$conditionReqProc);
        }
        /*$request_id = $_POST['request_id'];
        $requestProcess_id = $_POST['requestProcess_id'];
        */
    }else if($_POST['action']=="cancelRequest"){
        //tbrequest
        $update = array(
            "status"=>3
            );
        $condition = array(
            "id"=>$_POST['request_id']
            );
        $db->update("tbrequest",$update,$condition);
        
        $update2 = array(
            "status"=>3,
            "approver"=>0
            );
        $condition2 = array(
            "request_id"=>$_POST['request_id'],
            "status"=>0
            );
        $db->update("tbrequest_process",$update2,$condition2);
        echo 1;
    }
}
function tempGroupType($groupType){
    if($groupType=="Head"){
        return 1;
    }else if($groupType=="Assistant Head"){
        return 2;
    }
}
function tempName($name){
    $nameArray = explode(" ",$name);
    $return = "";
    if(count($nameArray)==2){
        $return = "(u.firstname='".$nameArray[0]."' and u.lastname='".$nameArray[1]."'";
    }else if(count($nameArray)==3){
        $return = "(u.firstname='".$nameArray[0]."' and u.middlename='".$nameArray[1]."' and u.lastname='".$nameArray[2]."'";
    }
    return $return.=" or p.position='$name')";
}
?>